import { Injectable } from "@nestjs/common"
import { PiracyEntity } from "./piracy.entity"
import { InjectRepository } from "@nestjs/typeorm"
import { ILike, Repository } from "typeorm"

@Injectable()
export class PiracyService {
  constructor(
    @InjectRepository(PiracyEntity)
    private readonly piracyEntity: Repository<PiracyEntity>
  ) {}

  /**
   * Obtain all piracy information
   * @param res
   */
  async getAll(res: any): Promise<void> {
    try {
      const data = await this.piracyEntity.find()
      res.json(data)
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Search piracy information
   * @param body
   * @param res
   */
  async search(body: any, res: any): Promise<void> {
    try {
      const data = await this.piracyEntity.find({
        where: [
          {
            app_name: ILike(`%${body.body}%`)
          },
          {
            domain: ILike(`%${body.body}%`)
          },
          {
            ip: ILike(`%${body.body}%`)
          }
        ]
      })
      res.json(data)
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Real deletion piracy information
   * @param body
   * @param res
   */
  async delete(body: any, res: any): Promise<void> {
    try {
      const { id } = body
      await this.piracyEntity.delete(id)
      res.json({ status: "success", message: "盗版信息删除成功！" })
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Batch real deletion piracy information
   * @param body
   * @param res
   */
  async deleteGroup(body: any, res: any): Promise<void> {
    const { ids } = body
    try {
      for (let i = 0; i < ids.length; i++) {
        await this.piracyEntity.delete(ids[i])
      }
      res.json({ status: "success", message: "盗版信息删除成功！" })
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * Record piracy information
   * @param data
   */
  async record(data: any): Promise<void> {
    try {
      const isExist = await this.piracyEntity.find({
        where: {
          app_name: data.app_name,
          app_id: data.app_id,
          domain: data.domain,
          ip: data.ip
        }
      })
      if (isExist.length === 0) {
        await this.piracyEntity.save(data)
      }
    } catch (err) {
      console.log(err)
    }
  }
}
